<template>
  <div class="upload">
    <div class="upload--btn" v-if="!imgList.length" @click="click">
      <img />
      <div>上传</div>
    </div>
    <template v-else>
      <div class="img-list" v-for="(item, index) in imgList" :key="index">
        <img :src="item" />
        <div class="remove" @click="remove"></div>
      </div>
    </template>
  </div>
</template>
<script setup>
import { ref } from 'vue';
const imgList = ref([]);
const click = () => {
  let input = document.createElement('input');
  input.setAttribute('type', 'file');
  input.setAttribute('accept', '.png, .jpg, .jpeg');
  input.onchange = () => {
    if (input.files) {
      imgList.value.push(window.URL.createObjectURL(input.files[0]))
    }
    input.remove();
    input = null;
  };
  input.click()
}
const remove = () => {
  for(let item of imgList.value){
    window.URL.revokeObjectURL(item)
  }
  imgList.value = [];
}
</script>
<style lang="less" scoped>
.upload {
  width: 80px;
  height: 80px;

  &--btn {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    font-size: 20px;
    background: #FFFFFF;
    color: #4A5060;
    border: 1px solid #E5E5E5;
    border-radius: 4px;
    line-height: 1;

    >img {
      margin-bottom: 5px;
      width: 28px;
      height: 24px;
    }
  }

  .img-list {
    position: relative;
    overflow: hidden;
    border-radius: 4px;

    >img {
      object-fit: contain;
      width: 80px;
      height: 80px;
    }

    .remove {
      position: absolute;
      top: 0;
      right: 0;
      width: 25px;
      height: 25px;
      background: rgba(0, 0, 0, .8);
      border-radius: 4px;

      &::before,
      &::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 17px;
        height: 2px;
        background-color: white;
      }

      &::before {
        transform: translate(-50%, -50%) rotate(45deg);
      }

      &::after {
        transform: translate(-50%, -50%) rotate(-45deg);
      }
    }
  }
}
</style>